package com.xyrl.project.app.util;

import com.xyrl.common.util.ObjectUtil;
import com.xyrl.project.common.authentication.JWTUtil;
import com.xyrl.project.common.authentication.LoginInfo;
import com.xyrl.project.common.constant.XyrlConstant;
import com.xyrl.project.common.csr.entity.CsrUser;
import com.xyrl.project.common.manager.UserManager;
import com.xyrl.project.common.system.entity.User;
import com.xyrl.project.common.util.SpringContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;

/**
 * 取得登录信息 只用于controller或同步线程中  如果是异步线程则获取不到
 *
 * @ClassName ShiroUtil
 * @Description TODO
 * @Author Administrator
 * @Date 2019/12/25 10:03
 * @Version 1.0
 */
public class ShiroUtil {
    /**
     * 取得登录帐号
     *
     * @return
     */
    public static String loginAccount() {
        // 保存日志
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        String username = "";
        if (StringUtils.isNotBlank(token)) {
            username = JWTUtil.getUsername(token);
        }
        return username;
    }

    /**
     * 取得登录帐号
     *
     * @return
     */
    public static LoginInfo loginInfo() {
        // 保存日志
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        LoginInfo loginInfo = null;
        if (StringUtils.isNotBlank(token)) {
            loginInfo = JWTUtil.getLoginInfo(token);
        }
        return loginInfo;
    }

    /**
     * 取得登录用户
     *
     * @return
     */
    public static User salemanUser() {
        UserManager userManager = SpringContextUtil.getBean(UserManager.class);
        // 通过用户名查询用户信息
        User user = userManager.getUser(loginAccount());
        return user;
    }

    /**
     * 取得登录用户
     *
     * @return
     */
    public static CsrUser customerUser() {
        UserManager userManager = SpringContextUtil.getBean(UserManager.class);
        // 通过用户名查询用户信息
        CsrUser user = userManager.getCustomer(loginAccount());
        return user;
    }

    /**
     * 取得登录用户id
     *
     * @return
     */
    public static Long loginUserId() {
        LoginInfo info = loginInfo();
        UserManager userManager = SpringContextUtil.getBean(UserManager.class);
        if (XyrlConstant.USER_TYPE_SALESMAN.equalsIgnoreCase(info.getUserType())) {
            // 通过用户名查询用户信息
            User user = userManager.getUser(info.getLoginName());
            if (ObjectUtil.isNotEmpty(user)) {
                return user.getUserId();
            }
        } else {
            // 通过用户名查询用户信息
            CsrUser user = userManager.getCustomer(info.getLoginName());
            if (ObjectUtil.isNotEmpty(user)) {
                return user.getId();
            }
        }
        return null;
    }
}
